<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Exceptions in Python</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, exceptions, programming, language, learn Python">
<meta name="description" content="In this part of the Python tutorial, we present
exceptions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Exceptions</h1>

<p>
In this part of the Python programming tutorial, we will talk about exceptions in Python.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
Errors detected during execution are called exceptions. During the execution of 
our application, many things might go wrong. A disk might get full and we cannot 
save our file. A internet connection might go down and our application tries to 
connect to a site. All these might result in a crash of our application. To prevent
 happening this, we must cope with all possible errors that might occur. For this, 
we can use the exception handling. 
</p>

<pre class="code">
>>> 3 / 0
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ZeroDivisionError: integer division or modulo by zero
</pre>

<p>
It is not possible to divide by zero. If we try to do this, a 
<code>ZeroDivisionError</code> is raised and the script is interrupted. 
</p>

<pre class="code">
$ cat zerodivision.py 
#!/usr/bin/python

# zerodivision.py


def input_numbers():
    a = float(raw_input("Enter first number:"))
    b = float(raw_input("Enter second number:"))
    return a, b

x, y = input_numbers()
print "%d / %d is %f" % (x, y, x/y)
</pre>

<p>
In this script, we get two numbers from the console. We divide these two numbers. 
If the second number is zero, we get an exception. 
</p>

<pre>
$ ./zerodivision.py 
Enter first number:2
Enter second number:0
Traceback (most recent call last):
  File "./zerodivision.py", line 12, in &lt;module&gt;
    print "%d / %d is %f" % (x, y, x/y)
ZeroDivisionError: float division
</pre>

<p>
We could handle this in two ways. 
</p>


<pre class="code">
#!/usr/bin/python

# zerodivision2.py


def input_numbers():
    a = float(raw_input("Enter first number:"))
    b = float(raw_input("Enter second number:"))
    return a, b


x, y = input_numbers()

while True:
    if y != 0:
        print "%d / %d is %f" % (x, y, x/y)
        break
    else:
       print "Cannot divide by zero"
       x, y = input_numbers() 
</pre>

<p>
First, we simply check that y value is not zero. If the y value is zero, we print a 
warning message and repeat the input cycle again. This way, we handled the error 
and the script is not interrupted. 
</p>

<pre>
$ ./zerodivision2.py 
Enter first number:4
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:6
5 / 6 is 0.833333
</pre>

<p>
The other way is to use exceptions. 
</p>

<pre class="code">
#!/usr/bin/python

# zerodivision3.py


def input_numbers():
    a = float(raw_input("Enter first number:"))
    b = float(raw_input("Enter second number:"))
    return a, b


x, y = input_numbers()

while True:
    try:
        print "%d / %d is %f" % (x, y, x/y)
        break
    except ZeroDivisionError:
       print "Cannot divide by zero"
       x, y = input_numbers() 
</pre>

<p>
After <code>try</code> keyword, we put the code, where we expect an 
exception. The <code>except</code> keyword catches the exception, 
if it is raised. We specify, what kind of exception we are looking for. 
</p>

<hr class="btm">

<pre>
except ValueError:
   pass
except (IOError, OSError):
   pass
</pre>

<p>
To handle more exceptions, we can either use more except keywords or place 
the exception names inside a tuple. 
</p>


<h2>Second argument of the except keyword</h2>

<p>
If we provide a second argument for the <code>except</code> keyword, 
we get a reference to the exception object. 
</p>

<pre class="code">
#!/usr/bin/python

# zero.py

try:
    3/0
except ZeroDivisionError, e:
    print "Cannot divide by zero"
    print "Message:", e.message
    print "Class:", e.__class__
</pre>

<p>
From the exception object, we can get the error message or the class name. 
</p>

<pre>
$ ./zero.py 
Cannot divide by zero
Message: integer division or modulo by zero
Class: &lt;type 'exceptions.ZeroDivisionError'&gt;
</pre>

<h2>The hierarchy of exceptions</h2>

<p>
The exceptions are organized in a hierarchy, being <code>Exception</code> the parent of all exceptions. 
</p>

<pre class="code">
#!/usr/bin/python

# interrupt.py

try:
    while True:
       pass
except KeyboardInterrupt:
   print "Program interrupted"
</pre>

<p>
The script starts and endless cycle. If we press Ctrl + C, we interrupt the cycle. 
Here, we caught the <code>KeyboardInterrupt</code> exception.
</p>

<pre>
Exception
  BaseException
    KeyboardInterrupt
</pre>

<p>
This is the hierarchy of the <code>KeyboardInterrupt</code> exception. 
</p>

<pre class="code">
#!/usr/bin/python

# interrupt.py

try:
    while True:
       pass
except BaseException:
   print "Program interrupted"
</pre>

<p>
This example works too. The <code>BaseException</code> also catches the 
keyboard interruption. Among other exceptions. 
</p>

<h2>User defined exceptions</h2>

<p>
We can create our own exceptions, if we want. We do it by defining a new exception class. 
</p>

<pre class="code">
#!/usr/bin/python

# b.py


class BFoundError(Exception):
   def __init__(self, value):
      print "BFoundError: b character found at position %d" % value

string = "You make me want to be a better man."


pos = 0
for i in string:
   if i == 'b':
      raise BFoundError, pos
   pos = pos + 1
</pre>


<p>
In our code example, we have created a new exception. The exception is derived 
from the base <code>Exception</code> class. Say we hate the b letter. 
And if we find any occurence of that letter in a string, we <code>raise</code>  our exception.
</p>

<pre>
$ ./b.py 
BFoundError: b character found at position 20
Traceback (most recent call last):
  File "./b.py", line 16, in &lt;module&gt;
    raise BFoundError, pos 
__main__.BFoundError
</pre>
 
<h2>The cleanup</h2>

<p>
There is a <code>finally</code> keyword, which is always executed. 
No matter if the exception is raised or not. 
It is often used to do some cleanup of resources in a program. 
</p>

<pre class="code">
#!/usr/bin/python

# cleanup.py

f = None

try:
   f = file('indaclub', 'r')
   contents = f.readlines()
   for i in contents:
      print i,
except IOError:
   print 'Error opening file'
finally:
   if f:
      f.close()
</pre>

<p>
In our example, we try to open a file. If we cannot open the file, an 
<code>IOError</code> is raised. In case we opened the file, we 
want to close the file handler. For this, we use the <code>finally</code> keyword.  
In the finally block we check if the file is opened or not. If it is opened, 
we close it. This is a common programming construct when we work with databases. 
There we similarly cleanup the opened database connections.
</p>


<p>
In this chapter, we have covered exceptions in Python.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 25, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

